$(function(){
    
    'use strict';
  
    var          hl,
           newsList = $('.news-headlines'),
      newsListItems = $('.news-headlines li'),
      firstNewsItem = $('.news-headlines li:nth-child(1)'),
        newsPreview = $('.news-preview'),
            elCount = $('.news-headlines').children(':not(.highlight)').length,
           vPadding = (parseInt(firstNewsItem.css('padding-top').replace('px', ''), 10)) +
                      (parseInt(firstNewsItem.css('padding-bottom').replace('px', ''), 10)),
            vMargin = (parseInt(firstNewsItem.css('margin-top').replace('px', ''), 10)) +
                      (parseInt(firstNewsItem.css('margin-bottom').replace('px', ''), 10)),
           cPadding = (parseInt($('.news-content').css('padding-top').replace('px', ''), 10)) +
                      (parseInt($('.news-content').css('padding-bottom').replace('px', ''), 10)),
              speed = 5000, // this is the speed of the switch in milliseconds
            myTimer = null,
           siblings = null,
        totalHeight = null,
            indexEl = 1,
                  i = null;
  
    // the css animation gets added dynamicallly so 
    // that the news item sizes are measured correctly
    // (i.e. not in mid-animation)
    // Also, appending the highlight item to keep HTML clean
    newsList.append('<li class="highlight nh-anim"></li>');
    hl = $('.highlight');
    newsListItems.addClass('nh-anim');
  
    function doEqualHeight(c) {
  
      if (newsPreview.height() < newsList.height()) {
        newsPreview.height(newsList.height());
      } else if ((newsList.height() < newsPreview.height()) && (newsList.height() > parseInt(newsPreview.css('min-height').replace('px', ''), 10))) {
        newsPreview.height(newsList.height());
      }
  
      if ($('.news-content:nth-child(' + c + ')').height() > newsPreview.height()) {
        newsPreview.height($('.news-content:nth-child(' + c + ')').height() + cPadding);
      }
    }
  
    function doTimedSwitch() {
  
      myTimer = setInterval(function () {
        if (($('.selected').index() + 1) === elCount) {
          firstNewsItem.trigger('click');
        } else {
          $('.selected').next(':not(.highlight)').trigger('click');
        }
      }, speed);
  
    }
  
    // when the user mouses over a news content item
    // the auto-switching will stop
    $('.news-content').on('mouseover', function () {
      clearInterval(myTimer);
    });
  
    // auto-switching starts again
    $('.news-content').on('mouseout', function () {
      doTimedSwitch();
    });
  
    function doClickItem() {
  
      newsListItems.on('click', function () {
  
        newsListItems.removeClass('selected');
        $(this).addClass('selected');
  
        siblings = $(this).prevAll();
        totalHeight = 0;
  
        // this loop calculates the height of individual elements, including margins/padding
        for (i = 0; i < siblings.length; i += 1) {
          totalHeight += $(siblings[i]).height();
          totalHeight += vPadding;
          totalHeight += vMargin;
        }
  
        // this moves the highlight vertically the distance calculated in the previous loop
        // and also corrects the height of the highlight to match the current selection
        hl.css({
          top: totalHeight,
          height: $(this).height() + vPadding
        });
  
        indexEl = $(this).index() + 1;
  
        $('.news-content:nth-child(' + indexEl + ')').siblings().removeClass('top-content');
        $('.news-content:nth-child(' + indexEl + ')').addClass('top-content');
  
        clearInterval(myTimer);
        // comment out doTimedSwitch() if you don't
        // want it to rotate automatically
        doTimedSwitch();
        doEqualHeight(indexEl);
      });
  
    }
  
    function doWindowResize() {
  
      $(window).resize(function () {
  
        clearInterval(myTimer);
        // click is triggered to recalculate and fix the highlight position
        $('.selected').trigger('click');
  
      });
  
    }
  
    // this is where everything gets initialized
    doClickItem();
    doWindowResize();
    $('.selected').trigger('click');






    var login = new Vue({
        el:'#loginBox',
        data(){
            var passneed = (value)=>{
                if(value.length<6||value.length>16)
                return false
                
                return true
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                  callback(new Error('请输入密码'));
                }else if(!passneed(value)) {
                    callback(new Error('密码的长度必须大于6位小于16位'))
                }   
                else {
                  if (this.registerMessage.user_password_again !== '') {
                    this.$refs.registerMessage.validateField('user_password_again');
                  }
                  callback();
                }
              };
            var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                
                callback(new Error('请再次输入密码'));
            }else if(!passneed(value)) {
                callback(new Error('密码的长度必须大于6位小于16位'))
            }  
            else if (value !== this.registerMessage.user_password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
            };

            var Numberpan = (value)=>{
                if(value.length!=11){
                    return false;
                }
                for(var i =0;i<value.length;i++){
                    if(value[i]>'9'||value[i]<'0')
                    return false;
                }
                return true;
            };
            var phoneNumber = (rule,value,callback) =>{
                if(value===''){
                    callback(new Error('请输入电话号码'));
                }else if(!Numberpan(value)){
                    callback(new Error('请输入正确的电话号码'));
                }else{
                    callback()
                }
            };
            var userName = (rule,value,callback)=>{
                if(value===''){
                    callback(new Error('请输入用户名！'));
                }else if(value.length<3||value.length>10){
                    callback(new Error('用户名需要大于3位小于10位'))
                }
                else{
                    callback();
                }
            }
            var useradress = (rule,value,callback)=>{
                if(value===''){
                    callback(new Error('请输入您的地址！'));
                }else{
                    callback();
                }
            }
            return{
                
                registerMessage:{//用户注册信息
                    user_name:"",
                    user_phone:"",
                    user_email:"",
                    user_address:"",
                    user_volunteer_state:"0",
                    user_info:"",
                    user_photo:"",
                    user_adopt_history:"0",
                    user_volunteer_info:"",
                    user_password:"",
                    user_password_again:'',
                },
                rules: {
                    user_password: [
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    user_password_again: [
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                    user_email:[
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    user_phone:[
                        { validator: phoneNumber, trigger: 'blur' }
                    ],
                    user_name:[
                        { validator: userName, trigger: 'blur' }
                    ],
                    user_address:[
                        { validator: useradress, trigger: 'blur' }
                    ]
                    
                },
                logginMessage:{
                    userlogin_name:"",
                    userlogin_password:"",
                    user_avater_url:'',
                },
                user_id:'',
                
            }
           
        },
        methods:{
            submitForm(formName) {
                
                this.$refs[formName].validate((valid) => {
                    
                  if (valid) {
                    axios.post("http://karrysmile.top/PetShelter/user/register", this.registerMessage).then(res => {
                    window.sessionStorage.setItem("user_id",JSON.stringify(res.data.data.user_id))
                    window.sessionStorage.setItem("userlogin_name",JSON.stringify(res.data.data.user_name))
                    window.sessionStorage.setItem("user_avater_url",JSON.stringify(res.data.data.user_photo))
                    window.location.href = "PetKnowledge.html";
                    
                })
                  } else {
                    return false;
                  }
                });
              },
              resetForm(formName) {
                this.$refs[formName].resetFields();
              },
            outLogin(){
                window.sessionStorage.removeItem('user_id');
                window.sessionStorage.removeItem('userlogin_name');
                window.sessionStorage.removeItem('user_avater_url');
                window.location.href = "PetKnowledge.html";
            },
            beforeUpload(file){
                const isJPG = file.type === "image/jpeg";
                const isPNG = file.type === "image/png";
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!(isJPG||isPNG)) {
                    this.$message.error('图片只能是JPG或PNG格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
                return (isJPG||isPNG) && isLt2M;
            },
            uploadSuccess(response, file){
                this.registerMessage.user_photo = response.data.imageUrl;
                this.$message({
                    type: response.flag ? 'success' : 'error',
                    message: response.message,
                })
            },
            // 获取sessionstorage里面的user_id
            getUser_id(){
                this.user_id = JSON.parse(window.sessionStorage.getItem('user_id'));
                this.logginMessage.userlogin_name = JSON.parse(window.sessionStorage.getItem('userlogin_name'));
                this.logginMessage.user_avater_url  = JSON.parse(window.sessionStorage.getItem('user_avater_url'));
            },
            // 登录注册框的显示功能
            Loginhandle(){
                
                    $('.login-box').show();
                    $('.mask').show();
                
                    $('.login-box #closeBtn').click(function(){
                        $('.login-box').hide();
                        $('.mask').hide();
                        $('.Register').hide();
                        $('.Login').show();
                    })
                
                    $('#GoRegister').click(function(){
                        $('.Register').show();
                        $('.Login').hide();
                
                        $('#registerpass').focus(function(){
                            // 点击密码框，获得焦点追加样式password
                            $('#reowl').addClass('password');
                        }).blur(function(){
                            // 移除样式password
                            $('#reowl').removeClass('password');
                        })
                        $('#registerpass1').focus(function(){
                            // 点击密码框，获得焦点追加样式password
                            $('#reowl').addClass('password');
                        }).blur(function(){
                            // 移除样式password
                            $('#reowl').removeClass('password');
                        })
                       
                    })
                    $('#GoLogin').click(function(){
                        $('.Register').hide();
                        $('.Login').show();
                
                    })
                    
                    $('#password').focus(function(){
                        // 点击密码框，获得焦点追加样式password
                        $('#owl').addClass('password');
                    }).blur(function(){
                        // 移除样式password
                        $('#owl').removeClass('password');
                    })
                    
                
            },
            loginButton(){
                axios.post("http://karrysmile.top/PetShelter/user/login", this.logginMessage).then(res => {
                    if(res.data.message == '不匹配错误'){
                        alert("密码错误")
                        return;
                    }else if(res.data.message=='该用户不存在'){
                        alert("该用户不存在")
                        return 
                    }else{
                        alert('登录成功')
                    }  
                    this.logginMessage.userlogin_name = res.data.data.user_name
                    this.logginMessage.user_avater_url = res.data.data.user_photo
                    this.user_id = res.data.data.user_id 
                    window.sessionStorage.setItem("user_id",JSON.stringify(res.data.data.user_id))
                    window.sessionStorage.setItem("user_avater_url",JSON.stringify(res.data.data.user_photo))						
                    window.sessionStorage.setItem("userlogin_name",JSON.stringify(res.data.data.user_name))						
                    $('.login-box').hide();
                    $('.mask').hide();
                    $('.Register').hide();
                    $('.Login').show();	
                })
            },
            
        },
        mounted() {
            this.getUser_id()
            
        },

    })

   

    var footer = new Vue({
        el:'#footer',
        data:{
            webinfo: {
                webinfo_id: '', 
                
                webinfo_phone: "", 
                
                webinfo_email: "", 
                
                webinfo_account: "  ", 
                
                webinfo_account_img: "", 
                
                webinfo_address: "", 
                
                webinfo_foot: "", 
                
                webinfo_beian: "" 
                 
                } 
        },
        methods: {
            getFooterMessage(){
                if(JSON.parse(window.sessionStorage.getItem('webinfo_id'))){
                    this.webinfo.webinfo_id = JSON.parse(window.sessionStorage.getItem('webinfo_id'));
                    this.webinfo.webinfo_phone = JSON.parse(window.sessionStorage.getItem('webinfo_phone'));
                    this.webinfo.webinfo_email = JSON.parse(window.sessionStorage.getItem('webinfo_email'));
                    this.webinfo.webinfo_account = JSON.parse(window.sessionStorage.getItem('webinfo_account'));
                    this.webinfo.webinfo_account_img = JSON.parse(window.sessionStorage.getItem('webinfo_account_img'));
                    this.webinfo.webinfo_address = JSON.parse(window.sessionStorage.getItem('webinfo_address'));
                    this.webinfo.webinfo_foot = JSON.parse(window.sessionStorage.getItem('webinfo_foot'));
                    this.webinfo.webinfo_beian = JSON.parse(window.sessionStorage.getItem('webinfo_beian'));
                    return 
                }else{
                    axios.get('http://karrysmile.top/PetShelter/webinfo/getWebinfo').then(res=>{
                        this.webinfo = res.data.data.webinfo
                        window.sessionStorage.setItem("webinfo_id",JSON.stringify(this.webinfo.webinfo_id))						
                        window.sessionStorage.setItem("webinfo_phone",JSON.stringify(this.webinfo.webinfo_phone))						
                        window.sessionStorage.setItem("webinfo_email",JSON.stringify(this.webinfo.webinfo_email))						
                        window.sessionStorage.setItem("webinfo_account",JSON.stringify(this.webinfo.webinfo_account))						
                        window.sessionStorage.setItem("webinfo_account_img",JSON.stringify(this.webinfo.webinfo_account_img))						
                        window.sessionStorage.setItem("webinfo_address",JSON.stringify(this.webinfo.webinfo_address))						
                        window.sessionStorage.setItem("webinfo_foot",JSON.stringify(this.webinfo.webinfo_foot))						
                        window.sessionStorage.setItem("webinfo_beian",JSON.stringify(this.webinfo.webinfo_beian))						

                    })

                }                 
            }
        },
        mounted() {
            this.getFooterMessage()
        },
    })

})